package queue;

import java.util.Iterator;

/**
 * @author swing
 * @description
 * @create 2022 - 11 - 22 10:57
 */
public class Queue<T> implements Iterable<T> {

    private Node head;
    private Node last;
    private int N;
    public Queue() {
        head = new Node(null,null);
        last=null;
        N=0;
    }
    private class Node {
        public T item;
        public Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
        /*
        1.public boolean isEmpty()：判断队列是否为空，是返回true，否返回false
        2.public int size():获取队列中元素的个数
        3.public T dequeue():从队列中拿出一个元素
        4.public void enqueue(T t)：往队列中插入一个元素
         */

    /**
     * @return
     */
    public boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }

    /**
     * 先进先出 采用链表实现
     *
     * @return
     */
    public void push(T t) {
        if (isEmpty()) {
            Node node = new Node(t, null);
            head.next = node;
            last = node;
//            last = new Node(t,null);
//            head.next=last;
        } else {
            Node oldLast = last;
            Node newLast = new Node(t, null);
            oldLast.next = newLast;
            last = newLast;
        }
        N++;
    }

    public T pop() {
        if (isEmpty()) {
            return null;
        } else {
            Node oldFirst = head.next;
            head.next = oldFirst.next;
            N--;
            if (isEmpty()){
                last=null;
            }
            return oldFirst.item;
        }
    }

    @Override
    public Iterator iterator() {
        return new QIteration();
    }

    private class QIteration implements Iterator {

        private Node n = head;
        @Override
        public boolean hasNext() {
            return n.next!=null;
        }
        @Override
        public T next() {
            Node node = n.next;
            n = n.next;
            return node.item;
        }
    }
}
